<template>
  <view class="lottery-page">
    <!-- Slogan区域 -->
    <view class="slogan-area">
      <text class="title-text" decode>吃什么？</text>
      <text class="slogan-text">随机一点，吃饭不纠结</text>
    </view>
    
    <!-- 抽签按钮区域 -->
    <view class="draw-area">
      <view v-if="isDrawing" class="animation-area">
        <text class="rolling-text">{{ rollingText }}</text>
      </view>
      
      <u-button 
        v-if="!isDrawing && !drawResult"
        type="primary" 
        size="large" 
        shape="circle"
        class="draw-button"
        @click="startDraw"
      >
        开始抽签
      </u-button>
    </view>
    
    <!-- 结果展示区域 -->
    <view v-if="drawResult && !isDrawing" class="result-area">
      <view class="result-card">
        <text class="restaurant-name">{{ drawResult.name }}</text>
        <view class="tags">
          <u-tag :text="drawResult.category" type="success" size="mini" />
          <!-- <u-tag :text="drawResult.frequency_rule" type="info" size="mini" /> -->
        </view>
        <text v-if="drawResult.notes" class="notes">{{ drawResult.notes }}</text>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <u-button type="default" size="normal" @click="redraw">重抽一次</u-button>
        <u-button type="warning" size="normal" @click="markWeek">这周不想吃</u-button>
      </view>
    </view>
    
    <!-- 空状态提示 -->
    <view v-if="showEmptyTip" class="empty-tip">
      <u-empty mode="data" text="暂无符合条件的餐厅" />
      <u-button type="primary" size="normal" @click="goToRestaurantPage">去添加餐厅</u-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { api } from '@/api'
import type { Restaurant, DrawResponse } from '@/api/types'

// 响应式数据
const isDrawing = ref(false)
const drawResult = ref<Restaurant | null>(null)
const rollingText = ref('')
const showEmptyTip = ref(false)

// 餐厅数据
const restaurants = ref<Restaurant[]>([])

// 滚动动画文本列表
const animationTexts = ref<string[]>(['正在加载...'])

// 加载餐厅数据
const loadRestaurants = async () => {
  try {
    const response = await api.restaurant.getAllRestaurants()
    restaurants.value = response?.data || []
    
    // 更新动画文本列表为真实餐厅名称
    if (restaurants.value.length > 0) {
      animationTexts.value = restaurants.value.map(r => r.name)
    } else {
      animationTexts.value = ['暂无餐厅数据']
    }
  } catch (error) {
    console.error('加载餐厅数据失败:', error)
    // 错误处理已在request.ts中统一处理
  }
}

// 开始抽签
const startDraw = async () => {
  try {
    if (restaurants.value.length === 0) {
      uni.showToast({
        title: '暂无餐厅数据',
        icon: 'none'
      })
      return
    }
    
    // 立即显示动画
    isDrawing.value = true
    drawResult.value = null
    
    // 并行执行抽签逻辑
    const drawPromise = api.draw.startDraw()
    
    // 播放动画并等待抽签结果
    const [animationResult, response] = await Promise.all([
      playRollingAnimation(),
      drawPromise
    ])
    
    // 显示结果
    if (response.data) {
      drawResult.value = response.data.restaurant
    }
    
    // 动画完成，停止loading状态
    isDrawing.value = false
    
  } catch (error) {
    console.error('抽签失败:', error)

    isDrawing.value = false
    // 错误处理已在request.ts中统一处理

      // 检查是否是没有符合条件的餐厅的错误
    if (error && typeof error === 'object' && 'message' in error) {
      const errorMessage = (error as any).message || ''
      if (errorMessage.includes('没有符合条件的餐厅') || errorMessage.includes('可以抽签')) {
        try {
          await api.draw.clearDrawHistory()
          uni.showToast({
            title: '已清空抽签历史，请重新开始',
            icon: 'success'
          })
        } catch (clearError) {
          console.error('清空历史失败:', clearError)
        }
      }
    }
  }
}

// 重新抽签
const redraw = async () => {
  try {
    // 立即显示动画
    isDrawing.value = true
    drawResult.value = null
    
    // 并行执行重抽逻辑
    const redrawPromise = api.draw.redraw()
    
    // 播放动画并等待重抽结果
    const [animationResult, response] = await Promise.all([
      playRollingAnimation(),
      redrawPromise
    ])
    console.log(response)
    // 显示结果
    if (response.data) {
      drawResult.value = response.data.restaurant
    }
    
    // 动画完成，停止loading状态
    isDrawing.value = false
    
  } catch (error) {
    console.error('重抽失败:', error)
    isDrawing.value = false
    debugger
    // 检查是否是没有符合条件的餐厅的错误
    if (error && typeof error === 'object' && 'message' in error) {
      const errorMessage = (error as any).message || ''
      if (errorMessage.includes('没有符合条件的餐厅') || errorMessage.includes('可以抽签')) {
        try {
          await api.draw.clearDrawHistory()
          uni.showToast({
            title: '已清空抽签历史，请重新开始',
            icon: 'success'
          })
        } catch (clearError) {
          console.error('清空历史失败:', clearError)
        }
      }
    }
    // 错误处理已在request.ts中统一处理
  }
}

// 标记今天不想吃
const markToday = async () => {
  if (!drawResult.value) return
  
  try {
    await api.mark.markToday(drawResult.value.id)
    uni.showToast({
      title: '已标记今天不想吃',
      icon: 'success'
    })
    
    // 自动重抽
    await redraw()
  } catch (error) {
    console.error('标记失败:', error)
    // 错误处理已在request.ts中统一处理
  }
}

// 标记这周不想吃
const markWeek = async () => {
  if (!drawResult.value) return
  
  try {
    await api.mark.markWeek(drawResult.value.id)
    uni.showToast({
      title: '已标记这周不想吃',
      icon: 'success'
    })
    
    // 自动重抽
    await redraw()
  } catch (error) {
    console.error('标记失败:', error)
    // 错误处理已在request.ts中统一处理
  }
}

// 播放滚动动画
const playRollingAnimation = (): Promise<void> => {
  return new Promise((resolve) => {
    let index = 0
    const interval = setInterval(() => {
      rollingText.value = animationTexts.value[index % animationTexts.value.length]
      index++
      
      if (index >= 20) { // 滚动20次，约3秒
        clearInterval(interval)
        resolve()
      }
    }, 150)
  })
}

// 跳转到餐厅管理页
const goToRestaurantPage = () => {
  uni.switchTab({
    url: '/pages/restaurant/restaurant'
  })
}

// 页面加载时初始化
onMounted(async () => {
  uni.showLoading({
    title: '加载中...'
  })
  
  try {
    await loadRestaurants()
  } catch (error) {
    console.error('初始化失败:', error)
    uni.showToast({
      title: '初始化失败',
      icon: 'error'
    })
  } finally {
    uni.hideLoading()
  }
})
</script>

<style scoped>
.lottery-page {
  box-sizing: border-box;
  min-height: calc(100vh - 50px);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0rpx;
}

.slogan-area {
  margin-top: 70rpx;
  margin-bottom: 50rpx;
}
.title-text {
  display: flex;
  justify-content: center;
  font-size: 48rpx;
  margin-bottom: 15px;
  font-weight: bold;
  color: #ffffff;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3)
}
.slogan-text {
  display: flex;
  justify-content: center;
  font-size: 36rpx;
  font-weight: bold;
  color: #ffffff;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

.draw-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 100rpx;
}

.animation-area {
  height: 200rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.rolling-text {
  font-size: 60rpx;
  margin-bottom: 150px;
  font-weight: bold;
  color: #ffffff;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.5);
  animation: bounce 0.3s ease-in-out;
}

@keyframes bounce {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

.draw-button {
  width: 300rpx;
  height: 300rpx;
  border-radius: 50%;
  font-size: 36rpx;
  font-weight: bold;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.3);
}

.result-area {
  width: 100%;
  max-width: 600rpx;
  margin-bottom: 100px;
}

.result-card {
  background: #ffffff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.1);
  text-align: center;
}

.restaurant-name {
  font-size: 48rpx;
  font-weight: bold;
  color: #333333;
  display: block;
  margin-bottom: 20rpx;
}

.tags {
  display: flex;
  justify-content: center;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.notes {
  font-size: 28rpx;
  color: #666666;
  display: block;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.empty-tip {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 40rpx;
}
</style>
